#!/usr/bin/python

# @brief Converts a Mif 2.5 file into a dotty script
# @author Robert Kirchgessner <kirchgessner@chrec.org>
# @date 2011-03-26

from xml.sax import *
import argparse
import sys
import networkx as nx

class Mif25Handler(ContentHandler):
  def __init__(self, data):
    ContentHandler.__init__(self)
    self.occur = 0
    self.pi = False
    self.str0 = ""
    self.proteinLabel = False
    self.data = data

  def startElement(self, name, attrs):
    if name == "interaction":
      self.p0 = ""
      self.p1 = ""

    if name == "proteinInteractor":
      self.pi = True

    if name == "shortLabel":
      if self.pi:
        self.proteinLabel = True;
  
  def endElement(self, name):
    if name == "interaction":
      self.data.add_interaction(self.p0, self.p1)

    if name == "shortLabel":
      if self.proteinLabel:
        if self.p0 == "":
	  self.p0 = self.str0
	else:
	  self.p1 = self.str0

	self.proteinLabel = False;
      
    if name == "proteinInteractor":
      self.pi = False

  def characters(self, chrs):
    self.str0 =  chrs

class MifData():
  def __init__(self):
    self.interactionList = list()

  def add_interaction(self, p0, p1):
    self.interactionList.append(dict({'p0': p0, 'p1' : p1}))

  def build_tree(self):
    g = nx.Graph()
    i = 0
    for s in self.interactionList:
      if i == 100:
        break
      g.add_edge(s['p0'], s['p1'])

    nx.write_dot(g, "test.dot")
  
  def nInt(self):
    print len(self.interactionList)

#Main function
def main(fname_in, fname_out):
  print "Input File: " + fname_in
  print "Output File: " + fname_out

  data = MifData()

  try:
    print "Parsing.."
    parse(fname_in, Mif25Handler(data))  
  except:
    print "Could not open file"
    return -1
 
  print "Parsing complete."
  
  print "Building tree.."
  data.build_tree()
  print "Tree building complete."


if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.add_argument( 'infile', action='store')
  parser.add_argument( 'outfile', action='store' )
  args = parser.parse_args(sys.argv[1:])
  main(args.infile, args.outfile)

